import pyaudio,wave
import numpy as np
import time
from wav2txt import get_text
#这个脚本可以用于录制声音，当声音大于500个单位开始录音
#安静后，再经过0.5s，如果这0.5s是安静的，0.5s后结束录音，并保存录音
#如果这0.5s不是安静的，那么继续录音直到安静
#安静后，再经过0.5s，如果这0.5s是安静的，0.5s后结束录音，并保存录音
#如果这0.5s不是安静的，那么继续录音直到安静
WAVE_OUTPUT_FILENAME = 'test.wav'
def save_audio(p,frames):
    wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
    wf.setnchannels(1)
    wf.setsampwidth(p.get_sample_size(pyaudio.paInt16))
    wf.setframerate(16000)
    wf.writeframes(b''.join(frames))
    wf.close()
def listen():
    mindb=500#最小声音，比这个音量大就录音，否则延迟0.5s结束
    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paInt16,channels=1,rate=16000,input=True,frames_per_buffer=1024)
    frames = []
    started_record=False
    change_state=False
    while True:
        data = stream.read(1024,exception_on_overflow = False)
        audio_data = np.frombuffer(data, dtype=np.short)
        sound_size = np.max(audio_data)
        
        if sound_size > mindb and not started_record:
            started_record =True
            start_record_time=time.time()
            print("start")
        if sound_size > mindb and started_record:
            frames.append(data)
        if sound_size<mindb and started_record and not change_state:
            sound_start_low_time=time.time()
            change_state=True
        if sound_size<mindb and started_record:
            if change_state:
                now=time.time() 
                if now-sound_start_low_time>0.5:
                    print(now-start_record_time)
                    save_audio(p,frames)
                    print(get_text())
                    print("end")
                    frames=[]
                    started_record=False
                    change_state=False
                else:frames.append(data)

    # stream.stop_stream()
    # stream.close()
    # p.terminate()
    
listen()
